import axios from 'axios'; // 引入axios
import {Loading, Message} from 'element-ui';
import {store} from '@/store/index'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000
})
let acitveAxios = 0
let loadingInstance
let timer
let resUuid = ''
const showLoading = () => {
    acitveAxios++
    if (timer) {
        clearTimeout(timer)
    }
    timer = setTimeout(() => {
        if (acitveAxios > 0) {
            loadingInstance = Loading.service({fullscreen: true})
        }
    }, 400);
}

const closeLoading = () => {
    acitveAxios--
    if (acitveAxios <= 0) {
        clearTimeout(timer)
        loadingInstance && loadingInstance.close()
    }
}
//http request 拦截器
service.interceptors.request.use(
    config => {
        showLoading()
        const token = store.getters['user/token']
        config.data = JSON.stringify(config.data);
        if (config.url === 'api-uaa/oauth/user/login') {
            config.headers = {
                'Content-Type': 'application/json',
                'uuid': resUuid,
                'clientType': 'webApp'
            }
        } else {
            config.headers = {
                'Content-Type': 'application/json',
                'Authorization': token,
                'clientType': 'webApp'
            }
        }

        return config;
    },
    error => {
        closeLoading()
        Message({
            showClose: true,
            message: error,
            type: 'error'
        })
        return Promise.reject(error);
    }
);


//http response 拦截器
service.interceptors.response.use(
    response => {
        closeLoading();
        if (response.config.url.includes('/api-uaa/oauth/captcha')) {
            resUuid = response.headers.uuid;
            return response.data;
        }
        //  console.log(response.headers.authorization)
        //  console.log(store)
        //  store.commit("user/setToken",response.headers.authorization)
        // // console.log(store.setToken(response.headers.authorization))
        //正常登录
        if (response.data.statusCode === 0 && (response.config.url.includes('/api-uaa/oauth/user/login')
            || response.config.url.includes('/api-uaa/oauth/user/code/token'))) {
            return response
        }
        if (response.data.statusCode === 0 || response.headers.success === "true") {
            // store.commit("user/setToken",response.headers.authorization)
            return response.data
        } else {
            Message({
                showClose: true,
                message: response.data.msg || decodeURI(response.headers.msg),
                type: 'error',
            })
            if (response.data.data && response.data.data.reload) {
                store.commit('user/LoginOut')
            }
            return Promise.reject(response.data.msg)
        }
    },
    error => {
        let errorMsg = "服务器内部错误,请联系管理员"
        if (error.response.status === 401) {
            store.commit("user/setToken", "")
            sessionStorage.clear()
            window.location.reload()
            errorMsg = "登录过期"
        }
        closeLoading()
        Message({
            showClose: true,
            message: errorMsg,
            type: 'error'
        })
        return Promise.reject(error)
    }
)

export default service
